package com.github.pig.goods.common.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.net.URL;
import java.util.Date;

/**
 * <p>
 * 文件上传
 * </p>
 * @Author: Carlos
 * @Date:2018/10/16 - 10:03 PM
 */
public class UploadFile {

    public static final String SecretId = "AKIDc5PhmePkxwlMjuFb6MNGxSkphLm0ipPn";
    public static final String SecretKey = "LURBi294mGXbT8aprgHgttgFcmiRxGNH";
    public static final String Region = "ap-guangzhou";
    public static final String BucketName = "kyb-pic-server";
    public static final String AppId = "1257189861";

    public static URL picCOS(File cosFile ,String fileType,String fileName) throws Exception {

        if (fileType == null) {
            fileType = "image";
        }

        COSCredentials cred = new BasicCOSCredentials(SecretId, SecretKey);
        // 2 设置bucket的区域, COS地域的简称请参照
        // https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(Region));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        String bucketName = BucketName + "-" + AppId;
        String key=null;
        if (fileName != null) {
            key = fileType+"/" + fileName + ".png";
        }else{
            key = fileType+"/" + System.currentTimeMillis() + ".png";
        }
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        // 指定要上传到 COS 上的路径

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, cosFile);
        cosClient.putObject(putObjectRequest);
        Date expiration = new Date(System.currentTimeMillis()+ 5 * 60 * 10000);
        URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
        cosClient.shutdown();
        return url;

    }
}
